from flask import Blueprint,request,jsonify
import json
from db import db1
from utils.acl import acl
from config import get_data
from utils.rs import rs
from utils.jwttoken import jwta
bp_user=Blueprint('bp_user',__name__)

@bp_user.route('/login',methods=['POST'])
def login():

    data=get_data()
    print(data,111)
    sql="select * from user where username='%s'"%(data['username'])
    res=db1.find(sql)
    password1=res['password']
    if password1==data['password']:
        # data1={"data":{'username':data['username']}}
        data1={'data':{'userid':res['id']}}

        token=jwta.jia_secret(data1)

        # 获取用户页面权限，接口权限
        pagelist=acl.get_page_relist(res['id'])
        interlist=acl.get_interface_relist(res['id'])
        print(interlist,"sdfghghdfgh")
        key='interface'+str(res['id'])
        rs.insertdata(key,*interlist)
        return jsonify({'code':200,'token':token,'userid':res['id'],'pagelist':pagelist,'username':res['username']})
    else:
        return jsonify({"code":404})

def getresdata(data):
    list=[]
    idlist={i["id"]: i for i in data if i["pid"] is None}
    for i in data:
        print(i["pid"])
        if i["pid"] is None:
            i["son"] = []
            list.append(i)
            continue
        if "son" not in idlist[i["pid"]]:
            idlist[i["pid"]]["son"] = []
        idlist[i["pid"]]["son"].append(i)
    return list



@bp_user.route('/getresource')
def getresource():
    uid=request.args.get('id')
    uid=int(uid)
    res=acl.get_resourcelist(uid)
    print(res,111)
    mes=getresdata(res)
    print(mes,222)
    return jsonify({"list":mes,"code":200})

# 角色互斥表
@bp_user.route('/addjiaose',methods=['POST'])
def addjiaose():
    data1=get_data()
    roleid=data1['roleid']
    uid=data1['uid']
    sql="select roleide from mutual where roleid=%d"%(roleid)
    res=db1.find_all(sql)
    if res:
        print(res,111)
        sql1="select * from user_role where userid=%d and roleid=%d"%(int(uid),int(res[0]['roleide']))
        res=db1.find_all(sql1)
        print(res,222)
        if res:
            return jsonify({'mes':'不能添加'})
    sql = "select roleid from mutual where roleide=%i"%(roleid)
    ree = db1.find_all(sql)
    print(ree,333)
    if ree:
        sql3="select * from user_role where userid=%d and roleid=%d"%(int(uid),int(ree[0]['roleid']))
        req=db1.find_all(sql3)
        if req:
            return jsonify({'mes': '不能添加3'})
    else:
        # 查询去重
        sql4="select * from user_role where userid=%d and roleid=%d"%(int(uid),int(roleid))
        res0=db1.find_all(sql4)
        print(res0,777)
        if res0:
            return jsonify({"mes":"已经有了，加不了了"})
        sql2="insert into user_role values(0,%d,%d)"%(int(uid),int(roleid))
        db1.update(sql2)
        print(666)
        return jsonify({'code':200})


@bp_user.route('/test1')
def test1():
    key='abac'
    rs.insert_hash(key,'ip','127.0.0.1')
    rs.insert_hash(key,'level','003')
    rs.insert_hash(key,'time',"['2021-10-10','2021-12-10']")
    values=rs.get_all_hash(key)
    print(values,1114444444444444444444444)
    for (k,v) in values.items():
        print(k,"asvbnm,nbfjhgf")
        if str(k,encoding='utf8')=='time':
            print(eval(v))
            print(eval(v)[0])
            print(eval(v)[1])
    return 'ok'


# 刷新客户资源
@bp_user.route('/getjiaozhi')
def getjiaozhi():

    uid=request.args.get('uid')
    uid=int(uid)
    print(type(uid),111)
    sql="select roleid from user_role where userid=%d"%(uid)
    res=db1.find_all(sql)
    if res:
        list1=[i['roleid'] for i in res]
        list2=[]
        for i in list1:
            sql1="select pid from role where id=%d"%(int(i))
            res1=db1.find(sql1)
            list2.append(res1['pid'])
            pid=max(list2)
            sql2="select id from role where pid=%d "%(int(pid))
            res3=db1.find(sql2)
            sql3="select resourceid from role_resource where roleid=%d"%(int(res3['id']))
            res4=db1.find_all(sql3)
            list3=[i['resourceid'] for i in res4]
            sql4="delete from user_resource where userid=%d"%(int(uid))
            db1.update(sql4)
            for i in list3:
                sql5="insert into user_resource values(0,%d,%d)"%(uid,int(i))
                db1.update(sql5)
            return 'ok666'
    return 'ok'

# 获取全部角色
@bp_user.route('/getallrole')
def getallrole():
    sql="select * from role"
    res=db1.find_all(sql)
    print(res,123)
    return jsonify({"code":200,'list':res})


@bp_user.route('/getholiday')
def getholiday():
    sql="select * from holiday_type"
    res=db1.find_all(sql)
    return jsonify({'code':200,'list':res})

# 获取数据源接口
@bp_user.route('/getresourcedata',methods=['POST','GET'])
def getresourcedata():
    if request.method=='GET':
        #从redis取，如果有直接返回
        values=rs.get_str('dataresouce')
        print(values)
        if values:
            list=eval(values)
        else:
        # 如果没有查询
            sql="select * from data_source"
            res=db1.find_all(sql)
            list=[]
            if res:
                for i in res:
                    dict={'id':i['id'],'name':i['name']}
                    sql1="select id,name,type from %s"%(i['tablename'])
                    subres=db1.find_all(sql1)
                    dict['mes']=subres
                    list.append(dict)
            # 存入redis
            rs.set_str('dataresouce',json.dumps(list))
        return jsonify({"code":200,'list':list})
    else:
        data=request.data
        if data:
            data=json.loads(data)
        else:
            data=request.form
        print(data,999)
        sql="update workflow set params='%s' where id=%d" % (data['mes'],int(data['id']))
        db1.update(sql)
        return jsonify({"code":200})

@bp_user.route('/getworkf')
def getworkf():
    id=request.args.get('id')
    sql="select * from workflow where id=%d"%(int(id))
    res=db1.find(sql)
    print(res,222)
    params = res["params"][0:-3]
    print(params)
    dict1={}
    for i in res:
        print(i,111)
        # dict1['id']=i.id
        # dict1['name']=i.name
        # dict1['status']=i.status
        # dict1['params']=params

    # print(dict1,777)
    return jsonify({"code":200,'workf':res})


# 角色配资源
@bp_user.route('/jiaogetz',methods=['POST'])
def jiaogetz():
    data=get_data()
    print(data,111)
    roleid=data['roleid']
    resourceid1=data['resourceid1']
    resourceid2=data['resourceid2']
    sql0="select * from role_resource where roleid=%d and resourceid=%d"%(roleid,resourceid1)
    res=db1.find(sql0)
    if res:
        sql1="select * from role_resource where roleid=%d and resourceid=%d"%(roleid,resourceid2)
        res1=db1.find(sql1)
        if res1:
            return jsonify({'mes':'已经有了，不用添加了'})
        else:
            sql2="insert into role_resource values(0,%d,%d)"%(roleid,resourceid2)
            db1.update(sql2)
            return jsonify({"mes":"添加成功"})
    sql3="insert into role_resource values(0,%d,%d)"%(roleid,resourceid1)
    db1.update(sql3)
    if resourceid2:
        sql4="insert into role_resource values(0,%d,%d)"%(roleid,resourceid2)
        db1.update(sql4)
    return jsonify({"mes":"添加成功","code":200})

#获取全部一级资源
@bp_user.route('/getallresource')
def getallresource():
    sql="select * from resource where pid=%d"%(0)
    res=db1.find_all(sql)
    return jsonify({"list":res,'code':200})

#获取全部2级资源
@bp_user.route('/getallresource2')
def getallresource2():
    id=request.args.get('id')
    sql="select * from resource where pid=%d"%(int(id))
    res=db1.find_all(sql)
    return jsonify({"list":res,'code':200})

# 获取客户已有角色
@bp_user.route('/getkerole')
def getkerole():
    userid=request.args.get('uid')
    sql="select * from user_role where userid=%d"%(int(userid))
    res=db1.find_all(sql)
    list1=[i['roleid'] for i in res]
    list2=[]
    for i in list1:
        sql1="select * from role where id=%d"%(int(i))
        res1=db1.find_all(sql1)
        print(res1,333)
        for j in res1:
            list2.append(j)
    print(list2,111)
    return jsonify({"list":list2,"code":200})

# 获取角色已有资源
@bp_user.route('/getroleyiyou')
def getroleyiyou():
    roleid=request.args.get('roleid')
    sql="select * from role_resource where roleid=%d "%(int(roleid))
    res=db1.find_all(sql)
    list1=[i['resourceid'] for i in res]
    list2=[]
    for i in list1:
        sql1="select * from resource where id=%d"%(i)
        res1=db1.find_all(sql1)
        for j in res1:
            list2.append(j)
    print(list2,111)
    return jsonify({"list":list2,"code":200})

# 删除角色已有的资源
@bp_user.route('/delroleres',methods=['POST'])
def delroleres():
    data=get_data()
    roleid=data['roleid']
    resourceid=data['id']
    sql0="select * from resource where pid=%d"%(resourceid)
    res=db1.find_all(sql0)
    if res:
        list1=[i['id'] for i in res]
        for i in list1:
            sql1="delete from role_resource where roleid=%d and resourceid=%d"%(roleid,int(i))
            db1.update(sql1)
    sql2="delete from role_resource where roleid=%d and resourceid=%d"%(roleid,resourceid)
    db1.update(sql2)
    return jsonify({"mes":"删除成功"})

# 删除用户角色和角色已有的资源
@bp_user.route('/delyongrole',methods=['POST'])
def delyongrole():
    data=get_data()
    userid=data['uid']
    roleid=data['id']
    sql0="select * from role_resource where roleid=%d"%(roleid)
    res=db1.find_all(sql0)
    list1=[i['id'] for i in res]
    for i in list1:
        sql1="delete from user_resource where userid=%d and resourceid=%d"%(userid,int(i))
        db1.update(sql1)
    sql="delete from user_role where userid=%d and roleid=%d"%(userid,roleid)
    db1.update(sql)
    return jsonify({"mes":"删除成功"})

# 获取用户
@bp_user.route('/getyonghu')
def getyonghu():
    sql="select * from user"
    res=db1.find_all(sql)
    print(res,111)
    return jsonify({"list":res})


def getdeptdata(data):
    tree = {}
    list = []
    for i in data:
        tree[i['id']] = i
    for j in data:
        pid = j['pid']
        if not pid:
            j['type'] = 1
            list.append(j)
        else:
            if 'children' not in tree[pid]:
                tree[pid]['children'] = []
            # 查询此部门下所有员工
            sql = "select * from user where id=%d" % (j['id'])
            res = db1.find_all(sql)
            userlist = []
            if res:
                for u in res:
                    u['type'] = 3
                    userlist.append(u)
            j['children'] = userlist
            j['type'] = 2
            tree[pid]['children'].append(j)

    return list


@bp_user.route('/getcomanyuser')
def getcomanyuser():
    # 获取所有公司及所有部门
    sql = "select * from treecompany"
    res = db1.find_all(sql)
    mes = getdeptdata(res)
    return jsonify({'code': 200, 'list': mes})
    # 数据重组，查询员工


@bp_user.route('/taskm', methods=['POST'])
def taskm():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    print(data,111)

    title = data['title']
    params = data['params']
    auditids = data['auditids']
    # 添加任务
    sql = "insert into tasks(title,params,next_audit,status,nexta) values('%s','%s','%s',1,%d)" % (
    title, params, auditids, auditids[0])
    db1.update(sql)

    sql1 = "select id,title from tasks where title='%s'" % (title)
    task = db1.find(sql1)
    # 把当前任务加到redis中，选用hash类型
    key = 'task%d' % (auditids[0])
    rs.insert_hash(key, task['id'], task['title'])
    return jsonify({"code": 200})


# 待我审批
@bp_user.route('/mytaskaudit')
def mytaskaudit():
    id = request.args.get('id')
    # 从redis中获取我的任务列表
    key = 'task%d' % (int(id))
    print(key)
    task = rs.get_all_hash(key)
    list = []
    for k, v in task.items():
        id = str(k, encoding='utf8')
        title = str(v, encoding='utf8')
        list.append({'id': id, 'title': title})

    return jsonify({"code": 200, 'list': list})





















